/*
 * NewJFrame.java
 *
 * Created on May 16, 2008, 10:55 AM
 */

package ca.jerg.app;

import ca.jerg.canvas.InternalFrame;
import ca.jerg.wizard.*;

import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.beans.PropertyVetoException;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import javax.swing.AbstractAction;
import javax.swing.JDesktopPane;
import javax.swing.JFileChooser;
import javax.swing.JMenuItem;
import javax.swing.JSeparator;

/**
 *
 * @author  dave
 */
public class jErg extends javax.swing.JFrame {
	
    /** Creates new form NewJFrame */
    public jErg() {
		eswl = new ErgSettingsWorkLoad();
		eswt = new ErgSettingsWorkTime();
		esrt = new ErgSettingsRestTime();
		esd = new ErgSettingsDescriptions();
		esc = new ErgSettingsCanvas();
		
		windowList = new ArrayList<InternalFrame>();
		windowListForward = new WindowListStep(this,true);
		windowListBackward = new WindowListStep(this,false);
		fileDialog = new JFileChooser();
		
		addWindowListener(new WindowAdapter() 
		{
			@Override
			public void windowClosing( WindowEvent we )
			{
				/*
				 * signal any internal frames that the
				 * master frame has been closed so do
				 * any saves as needed
				 */
				Iterator i = windowList.iterator();
				while ( i.hasNext() )
				{
					InternalFrame iFrame = (InternalFrame)i.next();
					iFrame.closeWindow();
				}
			}
		});
				
        initComponents();
		buildWindowList();
    }
	
	// <editor-fold defaultstate="collapsed" desc="Window List">
	public class WindowListStep extends AbstractAction
	{
		public WindowListStep( jErg parent, boolean forward )
		{
			this.parent = parent;
			this.forward = forward;
			
			if ( forward )
			{
				putValue(NAME,"Next");
				putValue(LARGE_ICON_KEY,ErgIcons.createLargeIcon(ErgIcons.NAVIGATION,"Forward"));
				putValue(SMALL_ICON,ErgIcons.createSmallIcon(ErgIcons.NAVIGATION,"Forward"));
			}
			else
			{
				putValue(NAME,"Previous");
				putValue(LARGE_ICON_KEY,ErgIcons.createLargeIcon(ErgIcons.NAVIGATION,"Back"));
				putValue(SMALL_ICON,ErgIcons.createSmallIcon(ErgIcons.NAVIGATION,"Back"));
			}
		}
		
		public void actionPerformed( ActionEvent e )
		{
			int size = parent.getWindowList().size();
			
			// with less then 2 internal frames there is nothing to do
			if ( size <= 1 )
				return;
			
			// get the currently selected internal frame
			InternalFrame iFrame = (InternalFrame)parent.getDesktopPane().getSelectedFrame();

			// find the currently selected frame in the list
			Iterator i = parent.getWindowList().iterator();
			int index = 0;
			while ( i.hasNext() )
			{
				if ( iFrame.equals((InternalFrame)i.next()) )
					break;
				
				index++;
			}
			
			InternalFrame next;
			if ( forward )
			{
				if ( ++index == size )
					index = 0;
			}
			else
			{
				if ( --index < 0 )
					index = size - 1;
			}
			
			next = parent.getWindowList().get(index);						
			parent.getDesktopPane().moveToFront(next);
			try
			{
				next.setSelected(true);
			}
			catch ( PropertyVetoException ex )
			{
			}
		}
		
		private jErg parent;
		private boolean forward;
	}
	
	public class WindowListAction extends AbstractAction
	{
		public WindowListAction( jErg parent, String name )
		{
			super(name);
			this.parent = parent;
			this.name = name;
		}

		public void actionPerformed( ActionEvent e )
		{
			Iterator i = windowList.iterator();
			while ( i.hasNext() )
			{
				InternalFrame iFrame = (InternalFrame)i.next();
				if ( iFrame.getTitle().equals(name) )
				{
					iFrame.moveToFront();
					try
					{
						iFrame.setSelected(true);
					}
					catch ( PropertyVetoException ex )
					{						
					}
				}
			}
		}
		
		private jErg parent;
		private String name;
	}
	
	public void buildWindowList()
	{
		windows.removeAll();
	
		windows.add(windowListForward);
		windows.add(windowListBackward);
		windows.add(new JSeparator());
		
		Iterator i = windowList.iterator();
		while ( i.hasNext() )
		{
			InternalFrame iFrame = (InternalFrame)i.next();
			JMenuItem menu = new JMenuItem(new WindowListAction(this,iFrame.getTitle()));			
			windows.add(menu);
		}
	}

	public void removeInternalFrame( InternalFrame obj )
	{
		windowList.remove(obj);
	}
	// </editor-fold>

	// <editor-fold defaultstate="collapsed" desc="Internal Frame Construction">
	public void newInternalFrame( File file )
	{
		InternalFrame iFrame = new InternalFrame(this,file);	
		constructInternalFrame(iFrame);
	}
	
	public void newInternalFrame( String title )
	{
		InternalFrame iFrame = new InternalFrame(this,title);	
		constructInternalFrame(iFrame);
	}
	
	private void constructInternalFrame( InternalFrame iFrame )
	{
		iFrame.setSize(600, 400);
		iFrame.setVisible(true);
		windowList.add(iFrame);

		desktopPane.add(iFrame);
		iFrame.moveToFront();
		try
		{
			iFrame.setSelected(true);
		}
		catch ( PropertyVetoException ex )
		{
		}		
	}
	// </editor-fold>
	
	private ArrayList<InternalFrame> windowList;
	private static int windowIndex = 0;
	private WindowListStep windowListForward;
	private WindowListStep windowListBackward;
	
	private ErgSettingsWorkLoad eswl;
	private ErgSettingsWorkTime eswt;
	private ErgSettingsRestTime esrt;
	private ErgSettingsDescriptions esd;
	private ErgSettingsCanvas esc;
	private JFileChooser fileDialog;

	// <editor-fold defaultstate="collapsed" desc="Accessors">
	public JDesktopPane getDesktopPane()
	{
		return desktopPane;
	}

	public void setDesktopPane( JDesktopPane desktopPane )
	{
		this.desktopPane = desktopPane;
	}

	public ArrayList<InternalFrame> getWindowList()
	{
		return windowList;
	}

	public void setWindowList( ArrayList<InternalFrame> windowList )
	{
		this.windowList = windowList;
	}
	// </editor-fold>
	


    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        desktopPane = new javax.swing.JDesktopPane();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenu4 = new javax.swing.JMenu();
        jMenuItem6 = new javax.swing.JMenuItem();
        jMenuItem7 = new javax.swing.JMenuItem();
        jMenuItem8 = new javax.swing.JMenuItem();
        jSeparator1 = new javax.swing.JSeparator();
        jMenuItem1 = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();
        jMenuItem2 = new javax.swing.JMenuItem();
        jMenuItem3 = new javax.swing.JMenuItem();
        jMenuItem4 = new javax.swing.JMenuItem();
        jMenuItem5 = new javax.swing.JMenuItem();
        jMenuItem9 = new javax.swing.JMenuItem();
        windows = new javax.swing.JMenu();
        jMenu3 = new javax.swing.JMenu();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("jErg");

        desktopPane.addContainerListener(new java.awt.event.ContainerAdapter() {
            public void componentAdded(java.awt.event.ContainerEvent evt) {
                desktopPaneComponentAdded(evt);
            }
            public void componentRemoved(java.awt.event.ContainerEvent evt) {
                desktopPaneComponentRemoved(evt);
            }
        });
        jScrollPane1.setViewportView(desktopPane);

        jMenu1.setText("File");

        jMenu4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/toolbarButtonGraphics/general/New24.gif"))); // NOI18N
        jMenu4.setMnemonic('n');
        jMenu4.setText("New");

        jMenuItem6.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK));
        jMenuItem6.setText("Quick Workout");
        jMenuItem6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                quickWorkoutAction(evt);
            }
        });
        jMenu4.add(jMenuItem6);

        jMenuItem7.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, java.awt.event.InputEvent.CTRL_MASK));
        jMenuItem7.setText("Custom Workout");
        jMenuItem7.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                newCustomWorkout(evt);
            }
        });
        jMenu4.add(jMenuItem7);

        jMenu1.add(jMenu4);

        jMenuItem8.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.event.InputEvent.CTRL_MASK));
        jMenuItem8.setIcon(new javax.swing.ImageIcon(getClass().getResource("/toolbarButtonGraphics/general/Open24.gif"))); // NOI18N
        jMenuItem8.setMnemonic('O');
        jMenuItem8.setText("Open");
        jMenuItem8.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                openCustomWorkout(evt);
            }
        });
        jMenu1.add(jMenuItem8);
        jMenu1.add(jSeparator1);

        jMenuItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F4, java.awt.event.InputEvent.ALT_MASK));
        jMenuItem1.setText("Exit");
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitAction(evt);
            }
        });
        jMenu1.add(jMenuItem1);

        jMenuBar1.add(jMenu1);

        jMenu2.setText("Settings");

        jMenuItem2.setMnemonic('L');
        jMenuItem2.setText("Work Loads");
        jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                workLoadAction(evt);
            }
        });
        jMenu2.add(jMenuItem2);

        jMenuItem3.setMnemonic('T');
        jMenuItem3.setText("Work Times");
        jMenuItem3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                workTimeAction(evt);
            }
        });
        jMenu2.add(jMenuItem3);

        jMenuItem4.setMnemonic('R');
        jMenuItem4.setText("Rest Times");
        jMenuItem4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                restTimeAction(evt);
            }
        });
        jMenu2.add(jMenuItem4);

        jMenuItem5.setMnemonic('D');
        jMenuItem5.setText("Descriptions");
        jMenuItem5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                descriptionAction(evt);
            }
        });
        jMenu2.add(jMenuItem5);

        jMenuItem9.setMnemonic('a');
        jMenuItem9.setText("Drawing");
        jMenuItem9.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                drawingAction(evt);
            }
        });
        jMenu2.add(jMenuItem9);

        jMenuBar1.add(jMenu2);

        windows.setText("Windows");
        jMenuBar1.add(windows);

        jMenu3.setText("Help");
        jMenuBar1.add(jMenu3);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 591, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 420, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void workLoadAction(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_workLoadAction
	if ( eswl.isShowing() == false )
	{
		eswl = new ErgSettingsWorkLoad();
		eswl.setVisible(true);
	}
	else
	{
		eswl.toFront();
		eswl.requestFocus();
	}
}//GEN-LAST:event_workLoadAction

private void workTimeAction(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_workTimeAction
	if ( eswt.isShowing() == false )
	{
		eswt = new ErgSettingsWorkTime();
		eswt.setVisible(true);
	}
	else
	{
		eswt.toFront();
		eswt.requestFocus();
	}
}//GEN-LAST:event_workTimeAction

private void restTimeAction(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_restTimeAction
	if ( esrt.isShowing() == false )
	{
		esrt = new ErgSettingsRestTime();
		esrt.setVisible(true);
	}
	else
	{
		esrt.toFront();
		esrt.requestFocus();
	}
}//GEN-LAST:event_restTimeAction

private void descriptionAction(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_descriptionAction
	if ( esd.isShowing() == false )
	{
		esd = new ErgSettingsDescriptions();
		esd.setVisible(true);
	}
	else
	{
		esd.toFront();
		esd.requestFocus();
	}
}//GEN-LAST:event_descriptionAction

private void quickWorkoutAction(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_quickWorkoutAction
	ErgWizard ew = new ErgWizard();
	ew.showWizard();
}//GEN-LAST:event_quickWorkoutAction

private void exitAction(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitAction
	this.processWindowEvent(new WindowEvent(this,WindowEvent.WINDOW_CLOSING));
}//GEN-LAST:event_exitAction

private void newCustomWorkout(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newCustomWorkout
	
	newInternalFrame("Unsaved-" + String.valueOf(windowIndex++));
}//GEN-LAST:event_newCustomWorkout

private void desktopPaneComponentRemoved(java.awt.event.ContainerEvent evt) {//GEN-FIRST:event_desktopPaneComponentRemoved
	buildWindowList();
}//GEN-LAST:event_desktopPaneComponentRemoved

private void desktopPaneComponentAdded(java.awt.event.ContainerEvent evt) {//GEN-FIRST:event_desktopPaneComponentAdded
	buildWindowList();
}//GEN-LAST:event_desktopPaneComponentAdded

private void openCustomWorkout(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_openCustomWorkout
	if ( fileDialog.showOpenDialog(this) == JFileChooser.APPROVE_OPTION )
	{
		newInternalFrame(fileDialog.getSelectedFile());
	}
}//GEN-LAST:event_openCustomWorkout

private void drawingAction(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_drawingAction
	if ( esc.isShowing() == false )
	{
		esc = new ErgSettingsCanvas();
		esc.setVisible(true);
	}
	else
	{
		esc.toFront();
		esc.requestFocus();
	}
}//GEN-LAST:event_drawingAction

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new jErg().setVisible(true);
            }
        });
    }
	
	
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JDesktopPane desktopPane;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenu jMenu3;
    private javax.swing.JMenu jMenu4;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JMenuItem jMenuItem3;
    private javax.swing.JMenuItem jMenuItem4;
    private javax.swing.JMenuItem jMenuItem5;
    private javax.swing.JMenuItem jMenuItem6;
    private javax.swing.JMenuItem jMenuItem7;
    private javax.swing.JMenuItem jMenuItem8;
    private javax.swing.JMenuItem jMenuItem9;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JMenu windows;
    // End of variables declaration//GEN-END:variables

}
